Assembly Language Programming 9

Shift Instructions


There are three types of Shift in Assembly Language :


Logical Shift

A logical shift causes the bit that 'falls off' to go into the carry flag, and a 0-bit to occupy tyhe vacant space.

  Register Contents   Carry Flag
Before 0 1 1 0 1 0 1 1   ?
After logical right shift 0 0 1 1 0 1 0 1   1

It is useful for examining the least significant bit of a number. After the shift, the carry bit can be tested and a conditional branch instruction executed.

Example SHR AL,1 Logical shifts right the AL register 1 place
  SHL AL,1 Logical shifts left the AL register 1 place

Arithmetic Shift

The sign bit always stays the same.

Shifting right is the equivalent of dividing a number by 2. Shifting left multiplies the number by 2.

  Register Contents   Carry Flag
Before 1 1 0 0 1 0 1 0   ?
After arithmetic right shift 1 1 1 0 0 1 0 1   0

 

Example SAR AL,1 Arithmetic shifts the AL register 1 place to the right.
  SAL AL,1 Arithmetic shifts the AL register 1 place to the left.

Cyclic Shift (Rotation)

The bit 'falling off' moves into the Carry flag and then moves into the vacant position.

  Register Contents   Carry Flag
Before 0 1 1 0 1 0 1 0   ?
After cyclic right shift 0 0 1 1 0 1 0 1   0

This is useful for performing a shift operation on large numbers (stored as several bytes).

Example ROR AL,1 Rotates the AL register 1 place to the right
  ROL AL,1 Rotates the AL register 1 place to the left

Exercise

What hexadecimal numbers would result by performing the following operations (use CAPITAL Letters)

Logical right shift on the hex number B9  
Logical left shift on the hex number 58  
Arithmetic right shift on the hex number 9C  
Cyclic right shift on 2C if Carry is 1  
A logical right shift on the hex number 3A9C